package com.sc.VenusQueryBeta.ui.fragments.account.xiadaikuan;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.zhouwei.library.CustomPopWindow;
import com.hengjun.kingstar.sdk.base.BasePresenter;
import com.hengjun.kingstar.sdk.base.fragment.BaseMVPCompatFragment;
import com.hengjun.kingstar.sdk.utils.LogUtils;
import com.hengjun.kingstar.sdk.utils.StringUtils;
import com.hengjun.kingstar.sdk.utils.ToastUtils;
import com.sc.VenusQueryBeta.R;
import com.sc.VenusQueryBeta.adapter.PopAdapter;
import com.sc.VenusQueryBeta.adapter.XiaDaiKuanAdapter;
import com.sc.VenusQueryBeta.constant.Constants;
import com.sc.VenusQueryBeta.contract.account.xiadaikuan.XiaDaiKuanContract;
import com.sc.VenusQueryBeta.model.bean.account.AccountList;
import com.sc.VenusQueryBeta.model.bean.account.CurrencyListBean;
import com.sc.VenusQueryBeta.model.bean.login.QueryRegisBean;
import com.sc.VenusQueryBeta.presenter.account.xiadaikuan.XiaDaiKuanPresenter;

import java.util.Calendar;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.header.MaterialHeader;

public class XiaDaiKuanFragment extends BaseMVPCompatFragment<XiaDaiKuanContract.XiaDaiKuanPresenter> implements XiaDaiKuanContract.IXiaDaiKuanView {


    private static XiaDaiKuanFragment fragment;
    @BindView(R.id.ibtn_xiadaikuan_back)
    ImageButton ibtnXiadaikuanBack;
    @BindView(R.id.vip_uservip_user_infornation)
    RecyclerView rvxiadaikuan;
    @BindView(R.id.ptr_class)
    PtrClassicFrameLayout ptrClass;
    @BindView(R.id.visible)
    TextView visible;
    @BindView(R.id.total_money)
    TextView totalMoney;
    @BindView(R.id.chooise_company)
    TextView chooiseCompany;
    @BindView(R.id.tv_daishu_money)
    TextView tvDaishuMoney;
    @BindView(R.id.all_sign)
    TextView allSign;
    private CustomPopWindow mCustomPopWindow;
    private XiaDaiKuanAdapter xiaDaiKuanAdapter;
//    private View headView;
    //    private TextView btn_choose_club;
    //  private TextView btn_choose_time;
    private CustomPopWindow mClubPopWindow;
    private PopAdapter popAdapter;
//    private String time1;
//    private String time2;
    private QueryRegisBean queryRegisBean;
    private int clientindex;
    private int roomId;
//    private TextView total_money;
//    private TextView all_sign;
//    private TextView daishu;
    private String roomyear;
    private String roommonth;
    private CurrencyListBean mallRoomListBean;//所有廳
    private RecyclerView clubrecyclerView;
    private float sum;
//    private View errorView;
    private String currency;


    public static XiaDaiKuanFragment newInstance(QueryRegisBean queryRegisBean, int clientindex, String currency_type) {
        Bundle args = new Bundle();
        args.putInt(Constants.CLIENTINDEX, clientindex);
        args.putSerializable(Constants.QUERY_SETTING, queryRegisBean);
        args.putString(Constants.CURRENCY_TYPE, currency_type);
        fragment = new XiaDaiKuanFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        if (queryRegisBean != null && !queryRegisBean.getServerSetting().getServerAddress().equals("")) {
            //查询所有厅
            showProgressDialog("正在加载...");
            mPresenter.queryAllCurrencyList(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort());
        } else {
            ToastUtils.showToast("数据异常");
            hideProgressDialog();
        }
    }

    /**
     * 初始化头部
     */
//    private void initHeadView() {
//        if (headView == null) {
//            headView = ResourcesUtils.inflate(R.layout.rv_top_xxdk);
//        }
//        if (errorView == null) {
//            errorView = ResourcesUtils.inflate(R.layout.view_network_error);
//        }
//        errorView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                mPresenter.queryClientReserved02(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
//                        clientindex, "", "", "5", "0", currency);
//            }
//        });
//        btn_choose_club = headView.findViewById(R.id.chooise_company);
//        total_money = headView.findViewById(R.id.total_money);  //合計
//        daishu = headView.findViewById(R.id.owe_money);  //貸贖
//        all_sign = headView.findViewById(R.id.all_sign);  //全線
//
//    }

    private void initClub() {
        View contentView = LayoutInflater.from(mActivity).inflate(R.layout.pop_list, null);
        //处理popWindow 显示内容

        //创建并显示popWindow
        mClubPopWindow = new CustomPopWindow.PopupWindowBuilder(mActivity)
                .setView(contentView)
                .create();
        clubrecyclerView = contentView.findViewById(R.id.recyclerView);

    }

    @Override
    public boolean onBackPressedSupport() {
        pop();
        return true;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_xia_dai_kuan;
    }

    @Override
    public void initData() {
        super.initData();
        if (fragment.getArguments() != null) {
            queryRegisBean = (QueryRegisBean) fragment.getArguments().getSerializable(Constants.QUERY_SETTING);
            clientindex = fragment.getArguments().getInt(Constants.CLIENTINDEX, 0);
            currency = fragment.getArguments().getString(Constants.CURRENCY_TYPE);
        }
    }

    /**
     * 下线贷款
     *
     * @param savedInstanceState savedInstanceState
     */
    @Override
    public void initUI(View view, @Nullable Bundle savedInstanceState) {
        //初始化一个空list的adapter，网络错误时使用，第一次加载到数据时重新初始化adapter并绑定recycleview
        chooiseCompany.setText(currency);
        xiaDaiKuanAdapter = new XiaDaiKuanAdapter(R.layout.item_xiadaikuan);
        rvxiadaikuan.setAdapter(xiaDaiKuanAdapter);
        rvxiadaikuan.setLayoutManager(new LinearLayoutManager(mActivity));
        Calendar c = Calendar.getInstance();//
        roomyear = String.valueOf(c.get(Calendar.YEAR)); // 获取当前年份
        roommonth = String.valueOf(c.get(Calendar.MONTH) + 1);// 获取当前月份
//        initHeadView();//初始化头部布局
        initClub();//初始化集團佈局
        reFreshListener();
    }

    @NonNull
    @Override
    public BasePresenter initPresenter() {
        return XiaDaiKuanPresenter.newInstance();
    }


    @OnClick({R.id.ibtn_xiadaikuan_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ibtn_xiadaikuan_back:
                pop();
                break;
        }
    }


    /**
     * 下拉刷新監聽
     */
    private void reFreshListener() {
        MaterialHeader header = new MaterialHeader(mContext);
        ptrClass.addPtrUIHandler(header);
        ptrClass.setLastUpdateTimeRelateObject(this);//设置刷新支持时间
        ptrClass.setResistance(1.7f);//设置下拉的阻尼系数，值越大感觉越难下拉
        ptrClass.setDurationToCloseHeader(1000);//设置刷新完成，头部回弹时间，注意和前一个进行区别
        ptrClass.setPullToRefresh(false);//设置下拉过程中执行刷新，我们一般设置为false
        ptrClass.setKeepHeaderWhenRefresh(true);//设置刷新的时候是否保持头部

        ptrClass.setPtrHandler(new PtrDefaultHandler() {               //下拉刷新
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                //模拟联网，延迟更新数据
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
//                      mAdapterWithHF.notifyDataSetChanged();//适配器更新数据
                        if (ptrClass != null && mPresenter != null) {
                            if (queryRegisBean != null && !queryRegisBean.getServerSetting().getServerAddress().equals("")) {
//                            xiaDaiKuanAdapter.removeAllHeaderView();//必須先remove headview
                                //查询子户口
//                                if (roommonth.equals("全年")) {
//                                    mPresenter.queryClientReserved02(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
//                                            clientindex, "", "", "5", "0", chooiseCompany.getText().toString());
//                                } else {
                                showProgressDialog("正在加載");
                                    mPresenter.queryClientReserved02(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
                                            clientindex, "", "", "5", "0", chooiseCompany.getText().toString());
//                                }
                            } else {
                                ToastUtils.showToast("数据异常");
                            }
                        } else {
                            hideProgressDialog();
                        }

                    }
                }, 1000);
            }
        });
    }


    @Override
    public void showNetworkError(Throwable throwable) {
        ptrClass.refreshComplete();//
//        xiaDaiKuanAdapter.setEmptyView(errorView);
        LogUtils.e("sdaddqweqweqweqeqw" + throwable);
        hideProgressDialog();
    }

    //查詢廳成功回調
    @Override
    public void showqueryAllCurrencyList(final CurrencyListBean currencyListBean) {
        if (currencyListBean != null && currencyListBean.getCurrencys().size() > 0) {
//            roomId = Integer.parseInt(currencyListBean.getRoomList().get(0).getRoomid());
            //填充廳數據
            //初始化一个空list的adapter，网络错误时使用，第一次加载到数据时重新初始化adapter并绑定recycleview
            popAdapter = new PopAdapter(R.layout.pop_list_item, currencyListBean);
            clubrecyclerView.setAdapter(popAdapter);
            clubrecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
            //集團點擊監聽
            popAdapter.setOnCliCkItemListenerr(new PopAdapter.OnCliCkItemListener() {
                @Override
                public void clickItem(int position) {
//                  roomId = Integer.parseInt(currencyListBean.getRoomList().get(position).getRoomid());
                    chooiseCompany.setText(currencyListBean.getCurrencys().get(position).getCurrencyName1());//動態改變集團名稱
                    //查詢子戶口
                    showProgressDialog("正在加载");
//                    xiaDaiKuanAdapter.removeAllHeaderView();
                    mPresenter.queryClientReserved02(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
                            clientindex, "", "", "5", "0", chooiseCompany.getText().toString());
                    mClubPopWindow.dissmiss();
                }
            });

            mallRoomListBean = currencyListBean;
//            roomId = allRoomListBean.getRoomList().get(0).getRoomid();//默认第一个厅
//            //查询子户口
            if (queryRegisBean != null && !queryRegisBean.getServerSetting().getServerAddress().equals("")) {
                //查询子户口
                mPresenter.queryClientReserved02(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
                        clientindex, "", "", "5", "0", chooiseCompany.getText().toString());
                LogUtils.e("canshuzhi=========:" + clientindex + "         " + roomId + "              " + roomyear + "             " + roommonth);
            }
        } else {
            hideProgressDialog();
        }
    }

//    /**
//     * 查詢廳成功回調
//     * @param allRoomListBean
//     */
//    @Override
//    public void showqueryAllRoomList(final AllRoomListBean allRoomListBean) {
//        if (allRoomListBean != null && allRoomListBean.getRoomList().size() > 0) {
//            roomId = Integer.parseInt(allRoomListBean.getRoomList().get(0).getRoomid());
//            //填充廳數據
//            //初始化一个空list的adapter，网络错误时使用，第一次加载到数据时重新初始化adapter并绑定recycleview
//            popAdapter = new PopAdapter(R.layout.pop_list_item, allRoomListBean.getRoomList());
//            clubrecyclerView.setAdapter(popAdapter);
//            clubrecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
//            //集團點擊監聽
//            popAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//                @Override
//                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                    roomId = Integer.parseInt(allRoomListBean.getRoomList().get(position).getRoomid());
//                    btn_choose_club.setText(allRoomListBean.getRoomList().get(position).getRoomname());//動態改變集團名稱
//                    //查詢子戶口
//                    showProgressDialog("正在加载");
////                    xiaDaiKuanAdapter.removeAllHeaderView();
//                    mPresenter.queryClientReserved02(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
//                            clientindex, roomId, "", "", "5", "0");
//                    mClubPopWindow.dissmiss();
//                }
//            });            //填充廳數據
//
//            mallRoomListBean = allRoomListBean;
////            roomId = allRoomListBean.getRoomList().get(0).getRoomid();//默认第一个厅
////            //查询子户口
//            if (queryRegisBean != null && !queryRegisBean.getServerSetting().getServerAddress().equals("")) {
//                //查询子户口
//                mPresenter.queryClientReserved02(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
//                        clientindex, roomId, "", "", "5", "0");
//                LogUtils.e("canshuzhi=========:" + clientindex + "         " + roomId + "              " + roomyear + "             " + roommonth);
//            }
//        } else {
//            hideProgressDialog();
//        }
//    }

    /**
     * 子户口查询成功回调
     *
     * @param accountListBean accountListBean
     */
    @Override
    public void showZiHuKouList(final AccountList accountListBean) {
//        xiaDaiKuanAdapter.removeAllHeaderView();
        //布局处理
        if (accountListBean != null && accountListBean.getClients() != null && accountListBean.getClients().size() > 0) {
            ptrClass.setVisibility(View.VISIBLE);
            visible.setVisibility(View.GONE);
        } else {
            visible.setVisibility(View.VISIBLE);
//            ptrClass.setVisibility(View.GONE);
        }
        initRvList(accountListBean);
        if (accountListBean != null && accountListBean.getClients() != null && accountListBean.getClients().size() > 0) {
            for (int i = 0; i < accountListBean.getClients().size(); i++) {
                if (accountListBean.getClients().get(i).getRedeemSum() != null && !accountListBean.getClients().get(i).getRedeemSum().equals("")) {
                    sum += Float.valueOf(accountListBean.getClients().get(i).getRedeemSum());
                    LogUtils.e("zhegezhishi============" + accountListBean.getClients().get(i).getRedeemSum());
                }
            }
        }
        xiaDaiKuanAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {//監聽item 劍點擊
                start(XiaDaiKuanFragment1.newInstance(queryRegisBean, Integer.parseInt(accountListBean.getClients().get(position).getClientindex()),chooiseCompany.getText().toString(),accountListBean.getClients().get(position).getClientid(),accountListBean.getClients().get(position).getClientnamecn()));

            }
        });





        chooiseCompany.setOnClickListener(new View.OnClickListener() {//选择集团監聽
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    mClubPopWindow.showAsDropDown(chooiseCompany, 0, 0, Gravity.CENTER);
                } else {
                    mClubPopWindow.showAsDropDown(chooiseCompany, 0, 0);
                }
            }
        });
        totalMoney.setText(StringUtils.FormatNumber(accountListBean.getCommonValueSum()+"") + "萬");//设置总金额
        allSign.setText(accountListBean.getLendlimitSum() + "萬");//設置全線
        tvDaishuMoney.setText(sum + "萬");//設置貸贖

//        xiaDaiKuanAdapter.addHeaderView(headView);//动态添加头部布局
        hideProgressDialog();
        ptrClass.refreshComplete();
    }

    /**
     * 填充户口适配器\
     *
     * @param accountListBean
     */
    private void initRvList(final AccountList accountListBean) {
        xiaDaiKuanAdapter = new XiaDaiKuanAdapter(R.layout.item_xiadaikuan, accountListBean.getClients());
        rvxiadaikuan.setAdapter(xiaDaiKuanAdapter);

    }


}
